package com.example.smartcitydemo.network.client

import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit

/**
 * @PACKAGE_NAME: com.example.smartcitydemo.network
 * @NAME: Caleb.F
 * @DATE: 2021/11/3 0:27
 * @Email: 1919796283@qq.com
 */
abstract class BaseRetrofit {
    private val okHttpClient: OkHttpClient
        get() {
            val builder = OkHttpClient.Builder()
            //日志拦截器
            val httpLogger = HttpLoggingInterceptor().apply {
                setLevel(HttpLoggingInterceptor.Level.BODY)
            }
            builder.connectTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .addInterceptor(httpLogger)
            return setHttpClientBuilder(builder).build()
        }


    //开放给子类去添加
    abstract fun setHttpClientBuilder(builder:OkHttpClient.Builder)
    :OkHttpClient.Builder
    //开放给子类去实现
    abstract fun  setRetrofitBuilder(retrofitBuilder: Retrofit.Builder)
    :Retrofit.Builder

    //获取api接口对象
    fun <T> getApi(clazz: Class<T>, baseUrl: String):T{
        Log.d("dede", "getApi: $baseUrl")
        val retrofitBuilder = Retrofit.Builder().baseUrl(baseUrl)
            .client(okHttpClient)
        return  setRetrofitBuilder(retrofitBuilder).build().create(clazz)
    }

}